package com.demo.touca.controller;

import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

import static java.lang.String.format;

@RequestMapping("/test")
@Controller
public class TestController {

    @Resource
    private ConfigurableApplicationContext context;

    @GetMapping("/job/run/{jobName}")
    @ResponseBody
    public String runJob(@PathVariable String jobName) {
        try {
            JobRegistry jobRegistry = context.getBean(JobRegistry.class);
            Job job = jobRegistry.getJob(jobName);
            JobLauncher jobLauncher = context.getBean(JobLauncher.class);
            JobExecution jobExecution = jobLauncher.run(job, createJobParams());
            if (!jobExecution.getExitStatus().equals(ExitStatus.COMPLETED)) {
                throw new RuntimeException(format("%s Job execution failed.", jobName));
            }
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(format("%s Job execution failed.", jobName));
        }
    }

    // 设置Job参数
    private static JobParameters createJobParams() {
        return new JobParametersBuilder().addString("p", "abc").addDate("date", new Date()).toJobParameters();
    }
}
